<?php

if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once BASE_PATH.'application/controllers/base'.EXT;

class Login extends Base {
	
       public function __construct()
       {
	      parent::__construct();
	      $this->load->model('usuariosdao');
	      $this->load->model("emaildao");
       }
       
       public function index()
       { 
	     $data = array(
			   "estado"	=> "Nothing to do"
		       );
	      echo json_encode($data);
       }
       public function valida($usuario,$password)
       {
	      if($usuario != "" && $password != ""){
		    $datosUsuario 	= $this->usuariosdao->isValid($usuario,$password);
		    if($datosUsuario){
			    $status = "conectado";
			    $id_usuario = $datosUsuario[0]['id_embarazada'];
		    }else{
			    $status = "desconectado";
			    $id_usuario = "Null";
		    }
	      }else{
		     $status = "Empty fields";
		     $id_usuario = "Null";
	      }
	      $data = array(
			   "estado"	    => $status,
                           "id_usuario"	    => $id_usuario
		       );
	      echo json_encode(array($data));
       }
       
       public function forgot(){

	      $correo_para_hash = $this->input->post("correo");
	      
	      if($correo_para_hash != ""){
		     
		     $hoy = date("Y-m-d");
		     $key_unique= $hoy.$correo_para_hash;
		     $MD4Hash=hash('md4',$key_unique);
		     $hash = hash('md5',$MD4Hash);
       
		     $is_updateHash = $this->usuariosdao->setHash($correo_para_hash,$hash);
		     if($is_updateHash){
			    
			    $data['toEmail'] = $correo_para_hash;
			    $data['subject'] = "You requested a new password‏ for your MyPregnancy account.";
			    $data['fromEmail'] = "equipo@miembarazo.com.mx";
			    $data['fromName'] = "The MyPregnancy Account Team";
			    $data['message'] = $this->emaildao->getForgotMessage($hash);
			    
			    if($this->emaildao->email($data))
				    $status = 1;
			    else
				    $status = 0;
				    
		     }else{
			       $status = 0;     
		     }
	      }else{
		     $status = 0;
	      }
	      
	      $data = array(
		    "estado"	    => $status
	      );
	      
	      header('Access-Control-Allow-Origin: *');
	      //echo json_encode(array($data));
	      echo $status;
       }
       public function restore(){
	      
	      $c = $this->input->post("correo");
	      $h = $this->input->post("hash");
	      $np = $this->input->post("nuevopassword");
	      $rp = $this->input->post("repitepassword");
	      
	      if( $c != "" && $h != "" && $np != "" && $rp != "" && $np == $rp){
		     $is_updatePassword = $this->usuariosdao->setPassword($c ,$h, $np);
		     if($is_updatePassword){
			    $status = 1;
		     }else{
			    $status = 0; 
		     }
	      }else{
		     $status = 0;   
	      }
	      
	      $data = array(
		    "estado"	    => $status
	      );
	      
	      header('Access-Control-Allow-Origin: *');
	      //echo json_encode(array($data));
	      echo $status;
       }
}

?>